package com.quandou.base.security;

import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.stereotype.Component;

@Component
@Order(value = 0)
public class AnyRequestAuthenticationAuthorizeConfigProvider implements AuthorizeConfigProvider {
    private UrlMetadataSource urlMetadataSource;
    private UrlAccessDecisionManager urlAccessDecisionManager;

    public AnyRequestAuthenticationAuthorizeConfigProvider(UrlMetadataSource urlMetadataSource, UrlAccessDecisionManager urlAccessDecisionManager) {
        this.urlMetadataSource = urlMetadataSource;
        this.urlAccessDecisionManager = urlAccessDecisionManager;
    }

    @Override
    public void config(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests().anyRequest().authenticated()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setSecurityMetadataSource(urlMetadataSource);
                        o.setAccessDecisionManager(urlAccessDecisionManager);
                        return o;
                    }
                });
    }
}
